/*
 * Copyright (c) 2006 - 2022, webrx.cn All rights reserved.
 *
 */
package cn.webrx;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * <p>Project: app2022 - File3
 * <p>Powered by webrx On 2022-01-17 17:47:55
 *
 * @author webrx [webrx@126.com]
 * @version 1.0
 * @since 17
 */
public class File3 {
    public static void main(String[] args) {
        String f = "my.txt";
        //字节流建立文件，并写入内容
        try {
            //覆盖方式，建立文件
            //FileOutputStream fos = new FileOutputStream(f);
            //追加方式，建立文件，如果文件存在，则文件指针移动到文件尾write写入数据
            FileOutputStream fos = new FileOutputStream(f, true);
            //fos.write("hello 中文效果\r\n".getBytes());
            fos.flush();
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        //字节流读取文件（文本文件）try with 会自动关闭流
        f = "C:\\app2022\\08io\\src\\main\\java\\cn\\webrx\\File3.java";
        try (var fis = new FileInputStream(f)) {
            byte[] buf = fis.readAllBytes();
            String txt = new String(buf);
            Pattern p = Pattern.compile(".*\\r\\n", Pattern.MULTILINE);
            Matcher m = p.matcher(txt);
            int num = 0;
            while (m.find()) {
                System.out.print(String.format("%02d. %s", ++num, m.group()));
            }
            //System.out.println();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
